package com.aop.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MethodAspect {
    public void printExecutionTime(JoinPoint joinPoint) {
        SimpleDateFormat format = new SimpleDateFormat("yy-MM-dd HH:mm:ss SSS");
        String now = format.format(new Date());
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        System.out.println("----->" + now + ":" + className + "." + methodName);
    }

    /**
     * <h2>返回后通知</h2>
     *
     * @param joinPoint
     * @param ret
     */
    public void afterReturnAdvice(JoinPoint joinPoint, Object ret) {
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        System.out.println("******>" + className + "." + methodName + ":" + ret);
    }

    public void afterAdvice(JoinPoint joinPoint) {
        System.out.println("******>后置通知执行");
    }

    public void afterExceptionAdvice(JoinPoint joinPoint, Throwable throwable) {
        System.out.println("******>异常通知" + throwable.getMessage());
    }

    /**
     * <h2>环绕通知</h2>
     *
     * @param joinPoint
     */
    public Object aroundService(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            long start = new Date().getTime();
            Object proceed = joinPoint.proceed();
            long end = new Date().getTime();
            long duration = end - start;
            if (duration >= 1000) {
                String className = joinPoint.getTarget().getClass().getName();
                String methodName = joinPoint.getSignature().getName();
                SimpleDateFormat format = new SimpleDateFormat("yy-MM-dd HH:mm:ss SSS");
                String date = format.format(new Date());
                System.out.println("------>" + date + "：" + className + "-->" + methodName);
            }
            return proceed;
        } catch (Throwable throwable) {
            throw throwable;
        }
    }

}
